package mongo

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func InsertData() {

	clientOptions := options.Client().ApplyURI("mongodb://guochuang:guochuang@192.168.3.213:27017")

	// 连接到MongoDB服务器
	client, err := mongo.Connect(context.Background(), clientOptions)
	if err != nil {
		fmt.Println("Failed to connect to MongoDB:", err)
		return
	}
	// 获取admin数据库
	license := client.Database("box").Collection("license")
	// 创建用户
	b := bson.M{"name": "ppp"}
	_, err = license.InsertOne(context.Background(), b)
	if err != nil {
		fmt.Println("插入数据失败")
		fmt.Println(err)
		return
	}
	// 关闭连接
	err = client.Disconnect(context.Background())
	if err != nil {
		fmt.Println("Failed to disconnect from MongoDB:", err)
		return
	}
}

func InsertUser(uri, user, pwd, db, role string) {

	clientOptions := options.Client().ApplyURI(uri)

	// 连接到MongoDB服务器
	client, err := mongo.Connect(context.Background(), clientOptions)
	if err != nil {
		fmt.Println("Failed to connect to MongoDB:", err)
		return
	}
	// 获取admin数据库
	adminDatabase := client.Database(db)
	// 创建用户
	createUserCommand := bson.D{
		{"createUser", user},
		{"pwd", pwd},
		{"roles", bson.A{bson.D{{"role", role}, {"db", db}}}},
	}
	createUserResult := adminDatabase.RunCommand(context.Background(), createUserCommand)
	if createUserResult.Err() != nil {
		fmt.Println("Failed to create user: ", createUserResult.Err())
		return
	}
	// 关闭连接
	err = client.Disconnect(context.Background())
	if err != nil {
		fmt.Println("Failed to disconnect from MongoDB:", err)
		return
	}
	fmt.Println("操作成功")
}
